const { app, BrowserWindow, Menu, dialog, globalShortcut } = require('electron')
// 去除顶部菜单栏
Menu.setApplicationMenu(null)
// 使用os获取当前可访问网络的mac 
let os = require('os')
function getIPAdressMac () {
  var interfaces = os.networkInterfaces();
  var interfacesArry = []
  for (let i in interfaces) {
    interfacesArry.push(interfaces[i]);
  }
  let interfacesArryone = [];
  for (let item of interfacesArry) {
    interfacesArryone.push(...item);
  }
  for (let i = 0; i < interfacesArryone.length; i++) {
    let currentItem = interfacesArryone[i]
    if (currentItem.family === 'IPv4' && currentItem.address !== '127.0.0.1' && !currentItem.internal) {
      return currentItem.mac;
    }
  }
}
const remoteIpMac = getIPAdressMac()
let mainWindow
// 创建窗口事件
function createWindow () {
  mainWindow = new BrowserWindow({ width: 1366, height: 768, minWidth: 1366, minHeight: 768, show: false, icon: './exe.ico' });
  if (remoteIpMac == undefined) {
    dialog.showMessageBox(mainWindow, {
      type: 'warning',
      title: '温馨提示',
      defaultId: 0,
      message: '网络未连接,请连接网络后再试!'
    })
  } else {
    let mac = remoteIpMac.toUpperCase().replace(/:/g, '-');
    mainWindow.loadURL(`file:${__dirname}/dist/index.html?mac=${mac}`)
    mainWindow.maximize();
    mainWindow.show()
    // 点击关闭按钮事件
    mainWindow.on('close', (e) => {
      e.preventDefault();
      dialog.showMessageBox(mainWindow, {
        type: 'info',
        title: '温馨提示',
        defaultId: 0,
        message: '您确定要关闭吗？',
        buttons: ['最小化', '直接退出'],
        cancelId: 2
      }).then((index) => {
        if (index.response === 0) {
          mainWindow.minimize();
        } else if (index.response === 1) {
          mainWindow = null;
          app.exit();
        }
      });
    })
  }
  mainWindow.on("focus", (e) => {
    globalShortcut.register('F5', function () {
      mainWindow.reload()
    })
  })
}

// // 设置只打开一个应用
const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
  app.quit()
} else {
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    // 当运行第二个实例时,将会聚焦到mainWindow这个窗口
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore()
      mainWindow.focus()
      mainWindow.show()
    }
  })
}
app.on('ready', function () {
  createWindow()
})
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})
app.on('activate', function () {
  if (mainWindow === null) createWindow()
})
app.on('browser-window-focus', function () {
  globalShortcut.register('F5', function () {
    mainWindow.reload()
  })
})
app.on('browser-window-blur', function () {
  globalShortcut.unregisterAll();
})






